<?php
namespace Common\Controller;
use Think\Controller;
use Common;

class BaseController extends Controller {

    public function __construct() {
        parent::__construct();

        //获取方法名称
        $action_name = strtolower(ACTION_NAME);
        //获取控制名称
        $controller_name = strtolower(CONTROLLER_NAME);
        //不用登陆的控制器
        $no_controller = array('crontab','onlineratifyloan');
        //不用登陆的方法
        $no_action = array('login');

        if (!session('cunpiao_data') && !in_array($action_name, $no_action) && !in_array($controller_name, $no_controller)) {
            //echo 999;exit;
            //redirect(U('Home/index/login'));
        }
    }


    //空操作
    public function _empty() {
        header("HTTP/1.0 404 Not Found");
        $this->display('./Application/Common/404/home404.html');
        exit;
    }


    /**
     * 返回并重载上一页
     * Transient_1988
     */
    public function goBack() {
        echo '<script>location.href = document.referrer;</script>';
        exit;
    }


    /**
     * 发送post请求
     * @param type $url
     * @param type $data
     * @return type
     */
    public function sendPost($url, $data = null) {
        $post_data = implode('&', $data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        ob_start();
        curl_exec($ch);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }

    /**
     * 发送get请求
     * @param type $url
     * @param type $data
     * @return type 失败返回false
     */
    public function sendGet($url, $data = null) {
        $status = false;
        if (empty($url)) {
            echo '亲，URL都没有，你要GET到哪去？';
            $status = false;
            return $status;
        }
        if (!empty($data)) {
            $get_data = '';
            foreach ($data as $k => $v) {
                $get_data .= "{$k}={$v}&";
            }
            $get_data = trim($get_data, '&');
        }
        if (!empty($get_data)) {
            $url .= '?' . $get_data;
        }
        $result = file_get_contents($url);
        if (!empty($result)) {
            $result = $this->jsonDecode($result);
        }
        return $result;

    }

    /**
     * 404操作
     */
    public function header404() {
        header("HTTP/1.0 404 Not Found");
        $this->display('./Application/Common/404/home404.html');
        exit;
    }

    /* 
     * 导出excel
     * $list array导出的数据
     * $rowtitle 设置excel第一行标题  例： $rowtitle = array(0=>'订单编号',1=>'用户名',2=>'送货方式');
     * $rowval 内容行对应$list中字段  例：$rowval = array('A'=>'order_sn','B'=>'user','C'=>'shipping_type');
     * $setwidth 各列内容的宽度  例：$setwidth = array('A'=>'25','B'=>'20','C'=>'20');
     * $title 导出的文件标题
     */
    public function pullExcel($list,$rowtitle,$rowval,$setwidth,$title='Excel导出'){
        vendor('PHPExcel');
        $objPhpExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPhpExcel);
        $objPhpExcel->getActiveSheet()->getDefaultColumnDimension()->setAutoSize(true);//设置单元格宽度
        foreach ($setwidth as $k=>$v){
            $objPhpExcel->getActiveSheet()->getColumnDimension($k)->setWidth($v);//设置表格的宽度手动
        }
        foreach ($rowtitle as $k=>$r){
            $objPhpExcel->getActiveSheet()->getStyleByColumnAndRow($k,1)->getFont()->setBold(true);//字体加粗
            $objPhpExcel->getActiveSheet()->setCellValueByColumnAndRow($k,1,$r);
            //$objPhpExcel->getActiveSheet()->getStyleByColumnAndRow('F')->getAlignment()->setWrapText(true);//自动换行
        }
        //设置当前的sheet索引 用于后续内容操作
        $objPhpExcel->setActiveSheetIndex(0);
        $objActSheet=$objPhpExcel->getActiveSheet();
        //设置当前活动的sheet的名称
        $objActSheet->setTitle($title);
        //设置单元格内容
        foreach($list as $k => $v){
            $num=$k+2;
            foreach ($rowval as $key=>$val){
                $objPhpExcel->setActiveSheetIndex(0)->setCellValue($key.$num, $v[$val]);
            }
        }
        $name=date('YmdHis').mt_rand(0, 9999);//设置文件名
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header("Content-Transfer-Encoding:utf-8");
        header("Pragma: no-cache");
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$title.'_'.urlencode($name).'.xls"');
        header('Cache-Control: max-age=0');
        ob_end_clean();
        $objWriter->save('php://output');
    }

    /*
     * 导入excel
     * $file EXECL文件路径
     * $rowval 每列对应字段名  例：$rowval = array('A'=>'goods_id','B'=>'name','C'=>'title');
     * 返回例示:array (size=总行数)
                    0 => 
                        array (size=3)
                            'goods_id' => A例的值
                            'name' => B例的值
                            'title' => C例的值
                    1 => 
                        array (size=3)
                            'goods_id' => A例的值
                            'name' => B例的值
                            'title' => C例的值
                    2=>...
     */
    public function pushExcel($file,$rowval){
        vendor('PHPExcel');//引入phpexcel类
        $objPhpExcel = new \PHPExcel();
        $objReader = new \PHPExcel_Reader_Excel2007();
        if(!$objReader->canRead($file)){
            $objReader = new \PHPExcel_Reader_Excel5();
            if(!$objReader->canRead($file)){
                exit('no Excel');
            }
        }
        $objPhpExcel = $objReader->load($file,$encode='utf-8');
        $sheet = $objPhpExcel->getSheet(0);
        $allRow = $sheet->getHighestRow(); // 取得总行数
        $allColumn = $sheet->getHighestColumn(); // 取得总列数
        $result = array();
        for($i=2;$i<=$allRow;$i++){
            $data = array();
            foreach ($rowval as $key=>$val){
                $data[$val] = $objPhpExcel->getActiveSheet()->getCell($key.$i)->getValue();
                $data[$val] = $data[$val] ? $data[$val] : '';
            }
            $result[] = $data;
        }
        return $result;
    }
}
